using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;

namespace OpenWaves
{
    public class BasicResolver : IResolver
    {
        private readonly Dictionary<Type, object> services = new Dictionary<Type, object>();

        public BasicResolver Register<TContract>(object implementation)
        {
            Contract.Requires<ArgumentNullException>(implementation != null);
            Contract.Requires(implementation is TContract, "Implementation does not implement contract.");
            Contract.Ensures(Contract.Result<BasicResolver>() != null);

            this.services[typeof(TContract)] = implementation;
            return this;
        }

        public bool TryResolve<T>(out T service) where T : class
        {
            object implementation = null;
            try
            {
                return this.services.TryGetValue(typeof(T), out implementation);
            }
            finally
            {
                service = (T)implementation;
            }
        }
    }
}